// Thread.cpp: implementation of the Thread class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Thread.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

Thread::Thread():
	m_hThread(NULL),
	m_dwThreadId(0),
	m_bActive(false)
{
}

Thread::~Thread()
{
	Kill();
}

bool Thread::CreateThread(DWORD dwCreateFlags, UINT nStackSize, LPSECURITY_ATTRIBUTES lpSecurityAttrs)
{
	m_hThread = ::CreateThread(lpSecurityAttrs,
		nStackSize,
		(LPTHREAD_START_ROUTINE)_ThreadFunc,
		(LPVOID)this,
		dwCreateFlags,
		(LPDWORD)&m_dwThreadId);

	if (m_hThread == NULL) return false;

	m_bActive = true;

	return true;
}

bool Thread::Wait()
{
	return WaitForSingleObject(m_hThread, INFINITE) == WAIT_OBJECT_0;
}

bool Thread::Kill()
{
	return ::TerminateThread(m_hThread, 1) != 0;
}

DWORD Thread::SuspendThread()
{
	m_bActive = false;

	return ::SuspendThread(m_hThread);
}

DWORD Thread::ResumeThread()
{
	m_bActive = true;

	return ::ResumeThread(m_hThread);
}

bool Thread::IsActive()
{
	return m_bActive;
}

DWORD Thread::_ThreadFunc(LPVOID pvThread)
{
	Thread * pThread = (Thread *)pvThread;

	DWORD dwRet = 0;
	if (pThread->InitInstance())
	{
		dwRet = pThread->Run();
	}
	pThread->ExitInstance();

	return dwRet;
}